<?php

namespace App\Controller\Admin;

use App\Controller\AbstractController;
use App\Service\Admin\LoginService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * 后台登录控制器
 * @Controller()
 * @package App\Controller\Admin
 */
class LoginController extends AbstractController
{
    /**
     * @Inject()
     * @var LoginService
     */
    protected $loginService;

    /**
     * 后台登录页面
     * @GetMapping("login")
     * @return ResponseInterface
     */
    public function login()
    {
        if ($this->session->get("admin")) {
            return $this->response->redirect("/admin/index/index");
        }
        return $this->render->render("admin.login.login");
    }

    /**
     * 登录验证
     * @PostMapping("login")
     */
    public function loginVerify()
    {
        $validator = $this->validation->make($this->request->all(), [
            'username' => 'required|between:5,20',
            'password' => 'required|between:5,20',
        ]);
        if ($validator->fails()) {
            return $this->baseResponse(1, $validator->errors()->first());
        }
        $data = $this->loginService->loginVerify($this->request->all(), $this->request->getServerParams()["remote_addr"]);
        return $this->baseResponse($data['code'], $data['message'], $data['data']);
    }

    /**
     * 后台登录页面
     * @RequestMapping(methods={"GET","POST"},path="logout")
     * @return ResponseInterface
     */
    public function logout()
    {
        $this->session->remove("admin");
        return $this->response->redirect("/admin/login/login");
    }
}